package com.msg.test.model;

import org.apache.commons.logging.LogFactory;
import org.apache.commons.logging.Log;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;

/**
 * Created by Administrator on 2017/10/19 0019.
 */
public class MsgHead {
    private Log log = LogFactory.getLog(MsgHead.class);
    private int totalLength; //消息总长度
    private int commandId; //命令或响应类型
    private int sequenceId; //消息流水号

    public MsgHead(){
        super();
    }

    public MsgHead(byte[] data){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        DataInputStream dataInputStream = new DataInputStream(byteArrayInputStream);
        try {
            this.setTotalLength(data.length+4);
            this.setCommandId(dataInputStream.readInt());
            this.setSequence(dataInputStream.readInt());
            dataInputStream.close();
            byteArrayInputStream.close();
        }catch (Exception ex){
        }
    }

    public byte[] toByteArray(){
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DataOutputStream dataOutputStream = new DataOutputStream(byteArrayOutputStream);
        try{
            dataOutputStream.writeInt(this.getTotalLength());
            dataOutputStream.writeInt(this.getCommandId());
            dataOutputStream.writeInt(this.getSequence());
            dataOutputStream.close();
        }catch (Exception ex){}
        return byteArrayOutputStream.toByteArray();
    }

    public int getTotalLength() {
        return totalLength;
    }

    public void setTotalLength(int totalLength) {
        this.totalLength = totalLength;
    }

    public int getCommandId() {
        return commandId;
    }

    public void setCommandId(int commandId) {
        this.commandId = commandId;
    }

    public int getSequence() {
        return sequenceId;
    }

    public void setSequence(int sequence) {
        this.sequenceId = sequence;
    }
}
